package com.llb666.java.jvm.model;

/**
 * 斐波那契数列
 */
public class Fibonacci {
    //F(0)=0,F(1)=1,当n>=2的时候，F(n) = F(n-1) + F(n-2),
    //F(2)=F(1) + F(0) = 1, F(3) = F(2) + F(1) = 1+1 = 2
    //F(0)-F(N) 依次为 0,1,1,2,3,5,8,13,21,34...
    private static int fibonacci(int n){
        if(n == 0) {return 0;}
        if(n == 1) {return 1;}
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
//    Exception in thread "main" java.lang.StackOverflowError
    public static void main(String[] args) {
//        System.out.println(fibonacci(10));
        fibonacci2(45);
    }


    static void fibonacci2(int n) {

        if(n < 0) {
            System.out.println("输入的n值错误！");
            return;
        }
        int f = 0;
        int k = 1;
        int temp;
        System.out.print("斐波那契数列为：");
        for(int i = 0 ; i < n ; i++) {
            if(i ==0){
                System.out.print(f + " ");
            }
            if(i == 1){
                System.out.print(k + " ");
            } else {
                System.out.print(k + " ");
                temp = k + f;
                f = k;
                k = temp;

            }

        }
        System.out.print(k);
        System.out.println();
        System.out.println(n + "对应的是：" +k);
    }
}
